<template>
  <div class="login">
    <el-row type="flex" justify="center">
      <el-col :span="8">
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model.number="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<style>
* {
  font-family: "Microsoft YaHei", "微软雅黑", Arial, Sans-serif,
  "Helvetica Neue", Helvetica,
  "PingFang SC", "Hiragino Sans GB";
}
</style>

<script>
export default {
  data() {
    var checkUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'));
      }
      callback();
    };
    var validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      }
      callback();
    };
    return {
      ruleForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          {validator: checkUsername, trigger: 'blur'}
        ],
        password: [
          {validator: validatePassword, trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('准备向服务器发起请求....');
          let url ='http://localhost:20000/myweb/login';
          console.log('请求路径：'+url);
          let data={
            username: this.ruleForm.username,
            password: this.ruleForm.password
          }
          console.log('请求参数：'+data);
          this.axios.post(url,data).then((response)=>{
            console.log(response)
            let responseBody = response.data;
            if(responseBody.state==200){
              console.log("响应的data:"+responseBody.data);
              this.$message({
                showClose: true,
                message: '登录成功',
                type: 'success'
              });
              this.$router.push('/admin')
            }else {
              console.log("响应的message："+responseBody.message);
              this.$message({
                showClose: true,
                message: responseBody.message,
                type: 'error'
              });
          }
          })
              .catch(function (error) {
                console.log(error)
              })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>